package com.jsyso.jadmin.common.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.jsyso.jadmin.common.config.Global;
import com.jsyso.jsyso.db.Dao;
import com.jsyso.jsyso.db.Wheres;
import com.jsyso.jsyso.db.id.Sequence;
import com.jsyso.jsyso.lang.JStringUtils;
import com.jsyso.jsyso.util.Callback;
import com.jsyso.jsyso.util.JsMap;
import com.jsyso.jsyso.util.jcollect.JCollect;

/**
 * 基础service
 * @author janjan, xujian_jason@163.com
 *
 */
public abstract class BaseService {
	public static final String SYS_CACHE = "sysCache";
	public static final String USER_CACHE = "userCache";
	protected abstract Dao dao();
	
	@Autowired
	protected Sequence seq;
	
	protected Wheres where() {
		return Wheres.create();
	}
	
	public JsMap get(Long id) {
		if(id == null || id < 1) {
			return null;
		}
		return this.get(JsMap.create(1).set("id", id));
	}

	public JsMap get(JsMap data) {
		if(data == null || data.isEmpty()) {
			return null;
		}
		return dao().find(data);
	}
	
	public List<JsMap> findList(JsMap data) {
		return findList(data, null);
	}
	
	public List<JsMap> findList(JsMap data, String order) {
		if(data == null) {
			return null;
		}
		return dao().order(order).select(data);
	}
	
	public JsMap findListPage(JsMap data, String order, int pageNo, int pageSize) {
		if(data == null) {
			return null;
		}
		// 总页数
		Long total = dao().count(data);
		// 数据list
		List<JsMap> list = dao().page(pageNo, pageSize).order(order).select(data);
		return JsMap.create("pages", (int)Math.ceil(total * 1.0d / pageSize)).set("list", list).set("pageNo", pageNo);
	}
	
	public int delete(JsMap data, boolean confirmDelete) {
		if(data == null || data.isEmpty()) {
			return 0;
		}
		return confirmDelete ? dao().delete(data) : dao().update(data);
	}
	
	public int delete(JsMap data) {
		data.set("del_flag", Global.YES);
		return this.delete(data, false);
	}
	
	public Long add(JsMap data) {
		if(data == null || data.isEmpty()) {
			return 0l;
		}
		Long id = seq.nextVal("sequence");
		if(id == null || id <= 0)
			return 0l;
		Date now = new Date();
		data.put("id", id);
		data.put("update_date", now);
		data.put("create_date", now);
		int result = dao().insert(data);
		return result > 0 ? id : 0l;
	}
	
	public int save(JsMap data) {
		if(data == null || data.isEmpty()) {
			return 0;
		}
		Date now = new Date();
		data.put("update_date", now);
		return dao().update(data);
	}
	
	public long count(JsMap data) {
		return dao().count(data);
	}
	
	public JsMap keyRename(JsMap data) {
		return JCollect.begin(data).renameAll(new Callback<String, String>() {
			public String handle(String param) {
				return JStringUtils.toUnderScoreCase(param, '_');
			}
		}).jsEnd();
	}
	
}
